package com.easybuilder.common.utils;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.easybuilder.common.enums.DingRobotEnum;
import com.taobao.api.ApiException;
import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class DingUtil {

    public static void sendRobotMsg(String url, String msg) {
        DingTalkClient client = new DefaultDingTalkClient(url);
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        request.setMsgtype("text");
        OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
        text.setContent(msg);
        request.setText(text);
        try {
            OapiRobotSendResponse response = client.execute(request);
            System.out.println("钉钉机器人消息返回结果：" + response.getBody() );
        } catch (ApiException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
        String value = DingRobotEnum.XTBG.getValue();
        Long timestamp = System.currentTimeMillis();
        String secret = "SECb69ce017165ae47528fa375cae50e13a6bd389b2cbf0f86b2b82f77d804ad358";

        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
        String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)),"UTF-8");
        System.out.println(sign);
        value += "&timestamp="+timestamp+"&sign="+sign;
        sendRobotMsg(value, "系统报告：\n  今日注册量：1; \n 总注册量：100; \n 今日在线人数：10 \n 今日产生bug：1");
    }
}
